<template>
  <el-cascader
    v-model="code"
    :options="tree"
    style="width: 100%"
    :show-all-levels="false"
    :props="{ value: 'code', label: 'name', emitPath: false,multiple: multiple, checkStrictly: true }"
    placeholder="请选择部门"
    @change="change"
    clearable
  ></el-cascader>
</template>

<script>
import { tenantTree } from '@/api/user';
export default {
  name: 'SelectGroup',
  props: {
    /* 部门Code */
    value: {
      type: [String, Number, Array],
      default: null
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tree: [],
      code: null
    };
  },
  watch: {
    value: {
      handler(val) {
        if(this.multiple) {
          this.code = val && val.split(',') ||[]
          return;
        }
        this.code = val || null;
      },
      immediate: true
    }
  },
  created() {
    this.getTree();
  },
  methods: {
    // 获取部门树
    getTree() {
      tenantTree().then((res) => {
        if(res.data && res.data.length) {
          const arrs = this.getTreeChild(res.data)
          // console.log("arrs", arrs)
          this.tree = arrs;
        }
      });
    },
    getTreeChild(childrenMap) {
      var children = JSON.parse(JSON.stringify(childrenMap))
      children.forEach((el, index) => {
        if (el.children && el.children.length) {
            el.children.forEach(c => {
              if (c.children && c.children.length) {
                c.children.forEach(u => {
                  u.children = null;
                })
                return
              }
            })
            return
        }
      })
      return children
    },
    change(e) {
      this.selectItem = null;
      this.getItem(this.tree, e);
      if(this.multiple) {
        this.$emit("input", e.join(','))
      }else{
        this.$emit('input', e);
      }
      this.$emit('change', this.selectItem);
    },
    // 递归查找树
    getItem(tree, id) {
      if (!tree || !tree.length) return null;
      if (!id) return null;
      if (this.selectItem) return null;
      const item = tree.find((i) => i.code == id);
      // console.log('查找结果：', item);
      if (item) {
        this.selectItem = item;
      } else {
        tree.map((item) => {
          this.getItem(item.children, id);
        });
      }
    }
  }
};
</script>

<style scoped lang="scss"></style>
